package merchant.dao;

import hackathon1212.EMF;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

public class ChargeDAO {

	private ChargeDAO(){

	}
	private static ChargeDAO singleton = new ChargeDAO();
	public static ChargeDAO get(){
		return singleton;
	}
	
	@SuppressWarnings("unchecked")
	public List<SummaryOfCharge> getSOCBySettlementId(final long settlementId){
		final EntityManager em = EMF.get().createEntityManager();
		final List<SummaryOfCharge> ret;
		try{
			final Query q = em.createQuery("select soc from SummaryOfCharge soc where " +
											"soc.settlementId = :SETTLEMENT");
			q.setParameter("SETTLEMENT", settlementId);
			ret =  q.getResultList();
		} finally {
			em.close();
		}
		for(final SummaryOfCharge soc : ret){
			final List<RecordOfCharge> rocs = ChargeDAO.get().getROCBySOCId(soc.getSocId());
			float sum = 0;
			for(final RecordOfCharge roc : rocs){
				sum += roc.getSubmittedLocalAmount();
			}
			soc.setAmount(sum);
		}
		return ret;
	}
	
	@SuppressWarnings("unchecked")
	public List<RecordOfCharge> getROCBySOCId(final long socId){
		final EntityManager em = EMF.get().createEntityManager();
		try{
			final Query q = em.createQuery("select roc from RecordOfCharge roc where " +
											"roc.socId = :SOC");
			q.setParameter("SOC", socId);
			return q.getResultList();
		} finally {
			em.close();
		}
	}
	
	public SummaryOfCharge getSOCById(final long socId){
		final EntityManager em = EMF.get().createEntityManager();
		try{
			return em.find(SummaryOfCharge.class, socId);
		} finally {
			em.close();
		}
	}
	
	public RecordOfCharge getROCById(final long rocId){
		final EntityManager em = EMF.get().createEntityManager();
		try{
			return em.find(RecordOfCharge.class, rocId);
		} finally {
			em.close();
		}
	}
	
	public SummaryOfCharge saveSOC(SummaryOfCharge toSave){
		final EntityManager em = EMF.get().createEntityManager();
		try{
			if(toSave.getSocId() == null){
				em.persist(toSave);
				return toSave;
			}else{
				return em.merge(toSave);
			}
		} finally {
			em.close();
		}
	}
	
	public RecordOfCharge saveROC(RecordOfCharge toSave){
		final EntityManager em = EMF.get().createEntityManager();
		try{
			if(toSave.getRocId() == null){
				em.persist(toSave);
				return toSave;
			}else{
				return em.merge(toSave);
			}
		} finally {
			em.close();
		}
	}	
}
